#region License Information (GNU GPL v3)

/*
    Super Meat Boy Stats
    Copyright (C) 2011 Juzz

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#endregion License Information (GNU GPL v3)

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using HelpersLibrary;
using Newtonsoft.Json;
using SuperMeatBoyLibrary;

namespace SMBStats
{
    public class SMBStatsWeb
    {
        public string UserKey { get; set; }

        private const string APIURL = "http://smbstats.muffinz.eu/api.php";
        private const string HashKey = "1502530b50a2768542b1a07aa5c32b04";

        private SMBManager smb;

        public SMBStatsWeb(SMBManager smbManager)
        {
            smb = smbManager;
        }

        public string Upload()
        {
            string result = null;

            if (smb != null && smb.IsLoaded && !string.IsNullOrEmpty(UserKey))
            {
                string json = JsonConvert.SerializeObject(smb);

                if (!string.IsNullOrEmpty(json))
                {
                    byte[] bytes = Encoding.ASCII.GetBytes(UserKey + json + HashKey);
                    string salt = BitConverter.ToString(new SHA1Managed().ComputeHash(bytes)).Replace("-", "").ToLowerInvariant();

                    Dictionary<string, string> arguments = new Dictionary<string, string>();
                    arguments.Add("userkey", UserKey);
                    arguments.Add("json", json);
                    arguments.Add("key", salt);

                    result = MyWebRequest.SendPostRequest(APIURL, arguments);
                }
            }

            return result;
        }
    }
}